/*
 * =============================================================================
 * Copyright by Benjamin Sempere,
 * All rights reserved.
 * =============================================================================
 * Author  : Benjamin Sempere
 * E-mail  : benjamin@sempere.org
 * Homepage: www.sempere.org
 * =============================================================================
 *
 * Licensed under the Apache License, Version 2.0 (the "License"); you may not
 * use this file except in compliance with the License. You may obtain a copy of
 * the License at
 *
 * http://www.apache.org/licenses/LICENSE-2.0
 *
 * Unless required by applicable law or agreed to in writing, software
 * distributed under the License is distributed on an "AS IS" BASIS, WITHOUT
 * WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied. See the
 * License for the specific language governing permissions and limitations under
 * the License.
 */
package org.sempere.commons.filter;

import org.apache.commons.lang.*;
import org.sempere.commons.base.*;
import org.sempere.commons.encryption.*;
import org.slf4j.*;

import javax.servlet.*;
import javax.servlet.http.*;
import java.io.*;

import static javax.servlet.http.HttpServletResponse.*;

/**
 * Filter that checks user authorization to access a web resource.<br/>
 * This filter relies on commons-security classes to achieve this job.
 *
 * @author sempere
 */
public abstract class AuthorizationFilter extends AbstractFilter {

	private static final Logger LOGGER = LoggerFactory.getLogger(AuthorizationFilter.class);
	private Encrypter encrypter;

	// *************************************************************************
	//
	// Constructors
	//
	// *************************************************************************

	public AuthorizationFilter() {
	}

	// *************************************************************************
	//
	// Methods from AbstractFilter class
	//
	// *************************************************************************

	@Override
	protected void initInternal() {
		LOGGER.debug("About to create encrypter instance from class [{}].", this.getEncrypterClass());
		this.encrypter = ReflectionHelper.newInstance(this.getEncrypterClass());
		LOGGER.debug("Encrypter instance from class [{}] created successfully.", this.getEncrypterClass());
	}

	@Override
	protected void destroyInternal() {
		LOGGER.debug("About to destroy encrypter instance from class [{}].", this.getEncrypterClass());
		this.encrypter = null;
		LOGGER.debug("Encrypter instance from class [{}] destroyed successfully.", this.getEncrypterClass());
	}

	// *************************************************************************
	//
	// Methods from Filter interface
	//
	// *************************************************************************

	public void doFilter(ServletRequest request, ServletResponse response, FilterChain chain) throws IOException, ServletException {
		LOGGER.debug("in doFilter");
		if (this.isValid(request)) {
			LOGGER.debug("User request is valid in term of authorizations.");
			chain.doFilter(request, response);
		}
		else {
			LOGGER.debug("User request is invalid in term of authorizations.");
			((HttpServletResponse) response).setStatus(SC_FORBIDDEN);
		}
	}

	// *************************************************************************
	//
	// Abstract methods
	//
	// *************************************************************************

	/**
	 * Return the current token stored in the client request (the token should be encrypted using the encrypter's encrypt method)
	 *
	 * @param request the client request
	 * @return String
	 */
	public abstract String getCurrentToken(ServletRequest request);

	/**
	 * Return the expected token (the token should be encrypted using the encrypter's encrypt method)
	 *
	 * @param request the client request
	 * @return String
	 */
	public abstract String getExpectedToken(ServletRequest request);

	/**
	 * Return the encrypter class to be used
	 *
	 * @return String
	 */
	public abstract String getEncrypterClass();

	// *************************************************************************
	//
	// Convenience methods
	//
	// *************************************************************************

	protected final boolean isValid(ServletRequest request) {
		String expectedToken = this.getExpectedToken(request);
		if (!StringUtils.isBlank(expectedToken)) {
			// Expected token
			String expectedClearToken = this.getEncrypter().decrypt(expectedToken);

			// Current token
			String currentClearToken = this.getEncrypter().decrypt(this.getCurrentToken(request));

			// Validation
			return expectedClearToken.equals(currentClearToken);
		}

		return true;
	}

	// *************************************************************************
	//
	// Getters and Setters
	//
	// *************************************************************************

	public Encrypter getEncrypter() {
		return encrypter;
	}
}